位置匹配

  1. 什么是位置?

    相邻字符之间的位置

  2. 如何匹配位置

    在ES5中,共有6个锚字符

    ^ $ \b \B (?=p) (?!p)

    es9支持后行断言, v8 4.9(chrome 62)支持后行断言.

    1. 脱字符和美元符号

      ^(脱字符)匹配开头,在多行匹配中匹配行开头。

      $(美元符号)匹配结尾,在多行匹配中匹配行结尾。

      练习1: "hello" -> "#hello#"

      answer

      练习2: "I\nlove\njavascript" -> 每一行行首和行尾都加#号

      answer
    2. \b和\B

      \b 代表什么?

      answer
      var result = "[JS] Lesson_01.mp4".replace(/\b/g, '#');
      
      console.log(result);
      
      answer
      var result = "[JS] Lesson_01.mp4".replace(/\B/g, '#');
      
      console.log(result);
      
      answer
    3. (?=p)和(?!p)

      匹配 : p前面的那个位置(更详细的解释在下面)

      练习1: "hello" -> "he#l#lo"

      answer

      练习2: "hello" -> "#h#ell#o#"

      answer
  3. 位置的特性

    位置理解成空字符

  4. 案例

    1. 不匹配任何

      answer
    2. 数字的千位分隔符表示

      • 弄出最后一个逗号

        answer
      • 弄出所有逗号

        answer
      • 不匹配开头

        answer
      • 支持其他形式: "12345678 123456789"

        answer
    3. 验证密码问题

      密码长度6-12位,由数字、小写字符和大写字母组成,但必须至少包括2种字符。

      1. 不考虑2种字符

        answer
      2. 判断是否包含有某一种字符

        answer
      3. 同时包含具体两种字符

        answer
      4. 用另一种方法解答: (?!p)

        answer

疑问

问题

console.log(obj.replace(/(?=(\d{3})+$)/g, ','))

解释

(?=pattern) 正向先行断言 : 代表字符串中的一个位置,紧接该位置之后的字符序列能够匹配pattern。

(?!pattern) 负向先行断言 : 代表字符串中的一个位置,紧接该位置之后的字符序列不能匹配pattern。

(?<=pattern) 正向后行断言 :代表字符串中的一个位置,紧接该位置之前的字符序列能够匹配pattern。

(?<!pattern) 负向后行断言 : 代表字符串中的一个位置,紧接该位置之前的字符序列不能匹配pattern。

参考:先行和后行断言

我的理解是

  • 对于先行断言(正向先行断言、负向先行断言),只使用美元符。
  • 对于后行断言(正向后行断言、负向后行断言),只使用脱字符。

为什么是“只使用”,不然会失去先行和后行断言的意义!

练习

ps: 字符串中不包含某个字符,用[^...]形式就可以了; 不包含某个字符串呢?只能使用负向断言了!

例如判断一句话中包含this,但不包含that。

我的答案:

var str = "that is this"

var r_has_this = /(?=(\bthis\b))/;

var r_not_that = /(?!(that))/ //思考为什么是true?应该怎么写?

。。。

未完待续。。。

作者答案:

。。。。

未完待续。。。

results matching ""

    No results matching ""